use bevy::{
    diagnostic::{Diagnostic, DiagnosticsStore, FrameTimeDiagnosticsPlugin},
    prelude::*,
};

pub struct FpsPlugin;

impl Plugin for FpsPlugin {
    fn build(&self, app: &mut App) {
        app.add_systems(Startup, setup_fps_ui)
            .add_systems(Update, update_fps_ui);
    }
}

#[derive(Component)]
struct ShowFpsText;

fn setup_fps_ui(mut commands: Commands, asset_server: Res<AssetServer>) {
    let font = asset_server.load("fonts/fusion-pixel.ttf");
    commands.spawn(Camera2d);
    commands.spawn((
        ShowFpsText,
        Text::default(),
        TextFont { font, ..default() },
        Node {
            position_type: PositionType::Absolute,
            top: Val::Px(12.0),
            right: Val::Px(12.0),
            ..default()
        },
    ));
}

fn update_fps_ui(mut text: Single<(&mut ShowFpsText, &mut Text)>, diag: Res<DiagnosticsStore>) {
    let Some(fps) = diag
        .get(&FrameTimeDiagnosticsPlugin::FPS)
        .and_then(Diagnostic::smoothed)
    else {
        return;
    };
    text.1.0 = format!("FPS: {:.0}", fps);
}
